// file-server.controller.ts
import { Controller, Get, Res, Param, NotFoundException } from '@nestjs/common';
// import { Response } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import { app } from 'electron'


@Controller()
export class FileController {
  @Get('file/*')
  async serveFile(@Res() res, @Param() params: any): Promise<void> {
    const filePath = params['*'];

    // console.log(params)

    if (!filePath) {
      throw new NotFoundException();
    }

    const destinationPath = app.getPath('userData') + '/UploadFile';

    // console.log(filePath)

    const absoluteFilePath = path.resolve(destinationPath, filePath);

    // console.log(absoluteFilePath)

    try {
      const stats = await fs.promises.stat(absoluteFilePath);

      // console.log(stats.isDirectory())

      if (stats.isDirectory()) {
        throw new NotFoundException();
      }

      const readStream = fs.createReadStream(absoluteFilePath);
      res.setHeader('Content-Type', 'application/octet-stream');
      res.setHeader('Content-Disposition', `attachment; filename="${path.basename(absoluteFilePath)}"`);
      readStream.pipe(res);

      // res.sendFile(absoluteFilePath);
    } catch (error) {
      throw new NotFoundException();
    }
  }
}
